#include "MeshFile.h"

namespace glow
{
	MeshFile::MeshFile(std::string fileName)
	//:IRessource(fileName)
	{
		_faces = 0;
		_mesh = 0;
		load(fileName);
	}
	
	/*
	 * Load in a float array the .off file. 
	 */
	void MeshFile::load(std::string fileName)
	{
		if (_mesh) 
		{
			delete[] _mesh;
			_mesh = 0;
		}
		if(_faces)
		{
			delete [] _faces;
			_faces = 0;
		}
		std::ifstream file(fileName.c_str(), std::ios::in);
		
		if (!file)
		{
			throw "Can't open file "+fileName;
		}
		
		
		//start reading the obj file.
		/* 
		 .off file example for a cube
OFF
8 6 0
-0.500000 -0.500000 0.500000
0.500000 -0.500000 0.500000
-0.500000 0.500000 0.500000
0.500000 0.500000 0.500000
-0.500000 0.500000 -0.500000
0.500000 0.500000 -0.500000
-0.500000 -0.500000 -0.500000
0.500000 -0.500000 -0.500000
4 0 1 3 2
4 2 3 5 4
4 4 5 7 6
4 6 7 1 0
4 1 7 5 3
4 6 0 2 4
*/
		std::string key;
		file >> key;
		if(key != "OFF")
		{
			file.close();
			throw (fileName+" is not a .off file");
		}
		
		int nbVertices, nbFaces, nbEdges, fSize, trash, count = 0;
		file >> nbVertices >> nbFaces >> nbEdges;
		_sizeV = nbVertices*3;
		_mesh = new float[_sizeV];
		
		for (int i = 0; i < _sizeV; i++)
		{
			file >> _mesh[i];
		}
		
		file >> fSize;
		_sizeF = fSize*nbFaces;
		_faces = new unsigned int[_sizeF];
		for (int i = 0; i < _sizeF; i++)
		{
		  count = (count + 1) % (fSize + 1);
		  if (count == 0)
		    {
		      count ++;
		      file >> trash;
		    }
		  file >> _faces[i];
		}
		file.close();
	}
	
	float * MeshFile::getVertices()
	{
		return _mesh;
	}
			
	unsigned int * MeshFile::getFaces()
	{
		return _faces;
	}
	
	int MeshFile::getVerticesSize()
	{
		return _sizeV;
	}
	
	int MeshFile::getFacesSize()
	{
		return _sizeF;
	}
	
	MeshFile::~MeshFile()
	{
		if(_mesh) delete [] _mesh;
		if(_faces) delete [] _faces;
	}
}
